"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import Link from "next/link";

interface Category {
  id: number;
  pid: number;
  type: string;
  name: string;
  createtime: number;
  updatetime: number;
  weigh: number;
  status: string;
}

interface Product {
  id: number;
  name: string;
  strength: string;
  price: number;
  image: string;
  category: string;
}

const products: Product[] = [
  {
    id: 1,
    name: "ZYN Icy Mint XX-Strong",
    strength: "12.5mg",
    price: 3.99,
    image: "https://cdn.gd.image.cn/images/2024/02/21/1.jpg",
    category: "Strong",
  },
  {
    id: 2,
    name: "ZYN Cool Mint Max Slim",
    strength: "12mg",
    price: 3.99,
    image: "https://cdn.gd.image.cn/images/2024/02/21/2.jpg",
    category: "Strong",
  },
  {
    id: 3,
    name: "ZYN Icy Blackcurrant XX-Strong",
    strength: "12.5mg",
    price: 3.99,
    image: "https://cdn.gd.image.cn/images/2024/02/21/3.jpg",
    category: "Strong",
  },
  {
    id: 4,
    name: "ZYN Citrus Slim Extra Strong",
    strength: "11mg",
    price: 3.99,
    image: "https://cdn.gd.image.cn/images/2024/02/21/4.jpg",
    category: "Extra Strong",
  },
  {
    id: 5,
    name: "ZYN Cool Frost Slim Strong",
    strength: "9mg",
    price: 3.99,
    image: "https://cdn.gd.image.cn/images/2024/02/21/5.jpg",
    category: "Medium",
  },
  {
    id: 6,
    name: "ZYN Fresh Mint Slim",
    strength: "6mg",
    price: 3.99,
    image: "https://cdn.gd.image.cn/images/2024/02/21/6.jpg",
    category: "Light",
  },
];

export default function ShopPage() {
  const router = useRouter();
  const [categories, setCategories] = useState<Category[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<number>(0); // 0 表示全部

  // 获取分类数据
  useEffect(() => {
    const fetchCategories = async () => {
      try {
        const response = await fetch(
          "http://shop_back.yankk.com.cn/index.php/api/goods/getcate"
        );
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        const data = await response.json();
        setCategories(data);
      } catch (error) {
        console.error("Error fetching categories:", error);
      }
    };

    fetchCategories();
  }, []);

  const addToCart = async (product: Product) => {
    try {
      // 1. 获取现有购物车数据
      const existingCart = localStorage.getItem("cart");
      const cart = existingCart ? JSON.parse(existingCart) : [];

      // 2. 检查商品是否已在购物车中
      const existingItemIndex = cart.findIndex(
        (item: any) => item.id === product.id
      );

      if (existingItemIndex >= 0) {
        // 如果商品已存在，增加数量
        cart[existingItemIndex].quantity += 1;
      } else {
        // 如果商品不存在，添加新商品
        cart.push({
          id: product.id,
          name: product.name,
          price: product.price,
          image: product.image,
          quantity: 1,
        });
      }

      // 3. 保存更新后的购物车数据
      localStorage.setItem("cart", JSON.stringify(cart));

      // 4. 显示成功提示（可以使用 toast 组件）
      alert("Added to cart successfully!");

      // 可选：直接跳转到购物车页面
      // router.push('/cart')
    } catch (error) {
      console.error("Error adding to cart:", error);
      alert("Failed to add to cart");
    }
  };

  return (
    <div>
      {/* 分类选项卡 */}
      <div className="relative mb-6">
        <div className="absolute left-0 top-0 bottom-0 w-8 bg-gradient-to-r from-white to-transparent pointer-events-none z-10"></div>
        <div className="absolute right-0 top-0 bottom-0 w-8 bg-gradient-to-l from-white to-transparent pointer-events-none z-10"></div>

        <div className="overflow-x-auto scrollbar-hide">
          <div className="flex whitespace-nowrap space-x-2 py-2 px-4">
            {/* 添加"全部"选项 */}
            <button
              className={`px-4 py-2 text-sm font-medium rounded-full min-w-max ${
                selectedCategory === 0
                  ? "bg-[#ffe4ed] text-[#ff4d8c]"
                  : "text-gray-600 hover:bg-[#fff5f8]"
              }`}
              onClick={() => setSelectedCategory(0)}
            >
              All Products
            </button>

            {/* 动态渲染分类按钮 */}
            {categories.map((category) => (
              <button
                key={category.id}
                className={`px-4 py-2 text-sm font-medium rounded-full min-w-max ${
                  selectedCategory === category.id
                    ? "bg-[#ffe4ed] text-[#ff4d8c]"
                    : "text-gray-600 hover:bg-[#fff5f8]"
                }`}
                onClick={() => setSelectedCategory(category.id)}
              >
                {category.name}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* 商品网格 */}
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4 md:gap-6">
        {/* 这里可以根据 selectedCategory 筛选商品 */}
        {products.map((product) => (
          <div key={product.id} className="border rounded-lg p-4">
            <div className="aspect-w-1 aspect-h-1 mb-4">
              <Image
                src={product.image}
                alt={product.name}
                fill
                className="object-cover rounded-lg"
              />
            </div>
            <h3 className="text-sm font-medium mb-2">{product.name}</h3>
            <div className="flex items-center justify-between">
              <span className="text-sm font-bold text-[#ff4d8c]">
                ${product.price.toFixed(2)}
              </span>
              <button
                onClick={() => addToCart(product)}
                className="bg-[#ff4d8c] text-white text-xs px-3 py-1 rounded hover:bg-[#ff3377] transition-colors"
              >
                Cart
              </button>
            </div>
          </div>
        ))}
      </div>

      {/* Warning Notice */}
      <div className="mt-16 text-center text-gray-500">
        <p className="text-sm">
          WARNING: This product contains nicotine. Nicotine is an addictive
          chemical.
        </p>
      </div>
    </div>
  );
}
